package jumpingnotes.restlet.resource;

import static jumpingnotes.restlet.ErrorCode.NO_PERMISSION;
import static jumpingnotes.restlet.ErrorCode.OBJECT_NOT_FOUND;
import static jumpingnotes.restlet.ErrorCode.SERVER_INTERNAL_ERROR;

import java.util.ArrayList;
import java.util.List;

import jumpingnotes.model.entity.ChapterVersion;
import jumpingnotes.restlet.JsonMapping;

import org.json.JSONObject;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;

public class ChapterVersionsValuesResource extends BaseResource
{
	private int chapterId;
	private String property;

	@Override
	public void init(Context context, Request request, Response response)
	{
		super.init(context, request, response);

		getVariants().add(new Variant(MediaType.APPLICATION_JSON));

		try
		{
			sessionId = (String) getRequest().getAttributes().get("sessionId");
			checkPermission();

			if (hasPermission())
			{
				// URL: "/chapters/{chapterId}/versions/{property}"
				chapterId = Integer.parseInt((String) getRequest().getAttributes().get("chapterId"));
				property = (String) getRequest().getAttributes().get("property");
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public Representation represent(Variant variant) throws ResourceException
	{
		if (!hasPermission())
		{
			return createErrorRepresentation(NO_PERMISSION);
		}

		if (property == null || property.trim().length() == 0)
		{
			return createErrorRepresentation(OBJECT_NOT_FOUND);
		}

		try
		{
			List<ChapterVersion> chapterVersionList = service.findValueByChapterIdAndProperty(chapterId, property);

			List<JSONObject> chapterVersionJsonList = new ArrayList<JSONObject>();
			for (ChapterVersion chapterVersion : chapterVersionList)
			{
				JSONObject chapterVersionJson = JsonMapping.map(chapterVersion);
				chapterVersionJsonList.add(chapterVersionJson);
			}

			JSONObject chapterVersionsJson = new JSONObject();
			chapterVersionsJson.put("chapterVersions", chapterVersionJsonList);

			return createJsonRepresentation(chapterVersionsJson);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return createErrorRepresentation(SERVER_INTERNAL_ERROR);
		}
	}
}
